package hhm.wechat.controller;

import java.util.Date;

import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import hhm.wechat.constants.Wechat;
import hhm.wechat.mybatis.mapper.WxMetaMapper;
import hhm.wechat.mybatis.pojo.WxMeta;
import hhm.wechat.pojo.AccessToken;
import hhm.wechat.utils.WeixinUtil;

@Controller
@RequestMapping("/token")
@ResponseBody
public class TokenController {

	@Autowired
	private WxMetaMapper mapper;

	/**
	 * 从微信处获取一个新的access_token，每天只能获取2000次
	 * 
	 * @param session
	 * @return
	 */
	@RequestMapping("/access_token/new")
	public Object access_token_new(HttpSession session) {

		AccessToken accessToken = new AccessToken();

		accessToken = WeixinUtil.getAccessToken();

		// 存入数据库
		if (!StringUtils.isEmpty(accessToken.getAccess_token())) {

			WxMeta record = new WxMeta();
			record.setMetaKey(Wechat.ACCESS_TOKEN);
			record.setMetaValue(accessToken.getAccess_token());
			record.setUpdateTime(new Date());
			mapper.updateByPrimaryKeySelective(record);

			// 存入session中
			session.setAttribute(Wechat.ACCESS_TOKEN, record);

		}

		return accessToken;

	}

	/**
	 * 从缓存中获取access_token
	 * 
	 * @param session
	 * @return
	 */
	@RequestMapping("/access_token/get")
	public Object access_token_get(HttpSession session) {

		WxMeta meta = new WxMeta();
		meta = (WxMeta) session.getAttribute(Wechat.ACCESS_TOKEN);
		return meta;

	}

}
